/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.mindorks.placeholderview;

import ohos.agp.components.Image;
import ohos.app.Context;
import ohos.app.dispatcher.TaskDispatcher;
import ohos.app.dispatcher.task.TaskPriority;
import ohos.media.image.ImageSource;
import ohos.media.image.PixelMap;
import ohos.media.image.common.PixelFormat;

import java.io.InputStream;
import java.lang.ref.WeakReference;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

/**
 * LoadImageInstance
 *
 * @since 2021-05-27
 */
public class LoadImageInstance {
    private volatile static LoadImageInstance mInstance;
    private TaskDispatcher mGlobalTaskDispatcher;
    private static Context mContext;

    private LoadImageInstance(Context context) {
        mGlobalTaskDispatcher = context.getGlobalTaskDispatcher(TaskPriority.DEFAULT);
        mContext = context;
    }

    /**
     * 实例化
     *
     * @param context 上下文
     * @return 实例化对象
     */
    public static LoadImageInstance getInstance(Context context) {
        if (mInstance == null) {
            synchronized (LoadImageInstance.class) {
                if (mInstance == null) {
                    mInstance = new LoadImageInstance(context);
                }
            }
        }
        return mInstance;
    }

    /**
     * 加载图片
     *
     * @param imageWeakReference 图片弱引用
     * @param urlImage 图片url
     */
    public void loadImageFromUrlAsync(WeakReference<Image> imageWeakReference, String urlImage) {
        if (mGlobalTaskDispatcher == null) {
            mGlobalTaskDispatcher = mContext.getGlobalTaskDispatcher(TaskPriority.DEFAULT);
        }

        mGlobalTaskDispatcher.asyncDispatch(new Runnable() {
            @Override
            public void run() {
                HttpURLConnection connection = null;
                try {
                    URL url = new URL(urlImage);
                    URLConnection urlConnection = url.openConnection();
                    if (urlConnection instanceof HttpURLConnection) {
                        connection = (HttpURLConnection) urlConnection;
                    }
                    if (connection != null) {
                        connection.connect();
                        // 之后可进行url的其他操作
                        // 得到服务器返回过来的流对象
                        InputStream inputStream = urlConnection.getInputStream();
                        ImageSource imageSource = ImageSource.create(inputStream, new ImageSource.SourceOptions());
                        ImageSource.DecodingOptions decodingOptions = new ImageSource.DecodingOptions();
                        decodingOptions.desiredPixelFormat = PixelFormat.ARGB_8888;
                        // 普通解码叠加旋转、缩放、裁剪
                        PixelMap pixelMap = imageSource.createPixelmap(decodingOptions);
                        PixelMap newPixelMap = ImageUtils.setRoundImage(pixelMap,
                                imageWeakReference.get().getWidth(),
                                imageWeakReference.get().getHeight());
                        // 普通解码
                        mContext.getUITaskDispatcher().syncDispatch(() -> {
                            imageWeakReference.get().setPixelMap(newPixelMap);
                            pixelMap.release();
                        });
                    }
                } catch (Exception e) {
                    e.fillInStackTrace();
                }
            }
        });
    }
}
